<template>
  <!-- 修改资料 -->

  <div>
    <el-form :model="form" label-position="right" ref="formRef">
        <ts-card>
        <template #header>
          <div style="display: flex; justify-content: space-between">
            <span>活动场次</span>
            <div style="display:flex">
            <el-button @click="initSchedule" type="primary">新 增</el-button>
            <el-button @click="deleteSchedules" :icon="Delete" type="danger" plain>删 除</el-button>
            </div>
          </div>
        </template>
        <el-table :data="dataList" @selection-change="selectSchedules">
            <el-table-column type="selection" width="45"></el-table-column>
          <el-table-column prop="name" label="场次名称"></el-table-column>
          <el-table-column prop="minutes" label="总时长"></el-table-column>
          <el-table-column prop="startDateTime" label="生效时间"></el-table-column>
          <el-table-column prop="endDateTime" label="截止时间"></el-table-column>
          <el-table-column prop="statusName" label="状态"></el-table-column>
          <el-table-column label="所有活动商品参与">
            <template #default="scope">
                <el-switch v-model="scope.row.allGoods" disabled/>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="60">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="editSchedules(scope.row)"
                >修 改</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </ts-card>
      <ts-card header="活动基本信息">
        <el-row :gutter="12">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="名称" required>
              <el-input v-model="form.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="时间范围" required>
              <el-date-picker
                v-model="form.dateTime"
                type="datetimerange"
                range-separator="To"
                format="YYYY/MM/DD hh:mm:ss"
                value-format="YYYY-MM-DD hh:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="时长" required>
              <el-input v-model="form.minutes" disabled>
                <template #append>分钟</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="所有活动商品参与" required>
              <el-switch v-model="form.allSchedules"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="状态">
              <el-select
                v-model="form.status"
                clearable
                placeholder="请选择："
              >
                <el-option
                  v-for="item in configData.statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </ts-card>
      <ts-card header="活动商品列表">
        <el-table ref="goodsListRef" :data="goodsList" @selection-change="selectGoods">
          <el-table-column type="selection" width="45"></el-table-column>
          <el-table-column prop="mtlName" label="商品名称"></el-table-column>
          <el-table-column prop="mtlNumber" label="商品编号"></el-table-column>
          <el-table-column
            prop="mtlKind"
            label="商品类别"
          ></el-table-column>
          <el-table-column prop="originalPrice" label="原价"></el-table-column>
          <el-table-column prop="stockQty" label="限售总数"></el-table-column>
          <el-table-column
            prop="minPurchaseQty"
            label="至多购买数"
          ></el-table-column>
          <el-table-column
            prop="couponCount"
            label="选中规则数"
          ></el-table-column>
        </el-table>
      </ts-card>
    </el-form>
    <div class="button-position">
      <el-button @click="updateVisible">退 出</el-button>
      <el-button type="primary" @click="addSchedule(formRef)">确 定</el-button>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted, nextTick,watch } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { deepClone } from "@/utils/arr";
import tsEditor from "@/components/scEditor/index.vue";
import Api from "@/api/model/mall";
const emit = defineEmits(["updatetable"]);
const props = defineProps({
  paramsData: {
    type: Object,
    defalut: {},
  },
});
// 添加用户数据的对象
const form = ref({});
const configData = ref({});
const dataList = ref([]);
const deleteList = ref([])
const goodsList = ref([])
const goodsListRef = ref(null)
const selectList = ref([]);
const formRef = ref(null);
watch(()=>form.value.dateTime, (New,Old)=>{
    if(New){
        form.value.minutes = getMinutesBetweenDates(New[0],New[1])
    }
    
})
onMounted(() => {
  getInit();
});

const updateVisible = () => {
  emit("updatetable");
};

const getInit = async (val) => {
  let res = await Api.promotion.schedule.add.post(props.paramsData);
  console.log(res);
  if (res.code == "200") {
    form.value = res.data;
    dataList.value = res.dataList;
    goodsList.value = res.goodsList
    configData.value = res.configData;
  }
};
const getMinutesBetweenDates=(startTimeString, endTimeString)=>{  
    // 创建日期对象  
    const startTime = new Date(startTimeString);  
    const endTime = new Date(endTimeString);  
  
    // 检查时间是否有效  
    if (isNaN(startTime.getTime()) || isNaN(endTime.getTime())) {  
        throw new Error('Invalid date strings');  
    }  
  
    // 确保结束时间晚于开始时间  
    if (endTime <= startTime) {  
        throw new Error('End time should be after start time');  
    }  
  
    // 计算时间差（毫秒）  
    const diffInMilliseconds = endTime - startTime;  
  
    // 转换为分钟  
    const diffInMinutes = Math.ceil(diffInMilliseconds / (1000 * 60)); // 使用Math.ceil来向上取整，得到完整的分钟数  
  
    return diffInMinutes;  
}
const selectSchedules = (rows)=>{
    deleteList.value = rows
}
const initSchedule = ()=>{
    getInit()
}
const editSchedules = async(val)=>{
    let  res = await Api.promotion.schedule.detail.post({id:val.id})
  if (res.code == "200") {
    form.value = deepClone(res.data);
    form.value.dateTime = [form.value.startDateTime,form.value.endDateTime]
    configData.value = res.configData;
    goodsList.value = res.goodsList
    goodsList.value.forEach((ele)=>{
        if(ele.selected){
            nextTick(()=>{
                goodsListRef.value.toggleRowSelection (ele,true);
            })
           
        }
        
    })
  }
}
const deleteSchedules = async () => {
  if (deleteList.value.length > 0) {
    let param = {
        rowIds: deleteList.value.map((ele) => {
        return ele.id;
      }),
    };
    ElMessageBox.confirm("确定删除吗？", "提示", {
      type: "warning",
      confirmButtonText: "确定",
      confirmButtonClass: "el-button--danger",
    })
      .then(async() => {
        console.log(param)
        let res =await Api.promotion.schedule.delete.post(param);
        if (res.code == 200) {
          ElNotification.success({ message: "删除成功", duration: 2000 });
          getInit()
        }
      })
      .catch(() => {});
  } else {
    ElMessage({
      message: "请选择表格记录",
      type: "warning",
    });
  }
}; 
const selectGoods = (rows)=>{
    selectList.value = rows
} 
const restAddFormData = () => {
  formRef.value.resetFields();
};

// 上传
const addSchedule = async (formRef) => {
  await formRef.validate((valid, fields) => {
    if (valid) {
      addScheduleData();
    }
  });
};

const addScheduleData = async () => {
  form.value.startDateTime = form.value.dateTime[0]
  form.value.endDateTime = form.value.dateTime[1]
  form.value.goodsIds = selectList.value
    .map((ele) => {
      return ele.id;
    })
    .toString();
  let params = {
    bean: form.value,
  };
    console.log(params);
    let res = await Api.promotion.schedule.saveOrUpdate.post(params);
    console.log(res);
    if (res.code == "200") {
      restAddFormData();
      selectList.value = []
      goodsList.value = []
      ElNotification.success({
        title: "",
        message: "操作成功！",
        duration: 2000,
      });
      getInit()
    }
};
</script>
      
      <style scoped></style>
      
      